package com.example.demo.Utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret}")
    private  String JWT_SECRET;

    @Value("${jwt.id}")
    private  String JWT_ID;

    @Value("${jwt.expiration}")
    private  Integer JWT_EXPIRATION;

    public  String createToken(String username){
        Date date = new Date();
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setId(JWT_ID)
                .setIssuedAt(date)
                .setExpiration(new Date(date.getTime()+JWT_EXPIRATION))
                .signWith(SignatureAlgorithm.HS256,JWT_SECRET)
                .compact();
    }

    public  String getUsernameByToken(String token){
        return parseToken(token).getSubject();
    }

    private  Claims parseToken(String token){
        Claims claims = null;
        try {
            claims =  (Claims) Jwts.parser()
                    .setSigningKey(JWT_SECRET)
                    .parse(token)
                    .getBody();
        }catch (ExpiredJwtException e){
            claims = e.getClaims();
        }
        return claims;
    }

    public boolean isExpiration(String token){
        return parseToken(token).getExpiration().before(new Date());
    }


}
